<?php

namespace app\v1\controller;
use support\Request;
use app\model\CompanyModel;
use app\model\CompanyMasterModel;
use app\model\UserModel;
use app\model\CardModel;
use app\model\CardItemModel;
use app\model\CardUserModel;
use app\model\CompanyKfModel;

class CompanyController {
    

    public function index(Request $request){
        $data = CompanyModel::whereNull('deleted_at')->get();

        return json([
            'code' => 1,
            'data' => $data,
        ]);
    }

    /**
     * 判断我是否是公司管理员
     * @param Request $request
     * @return \support\Response
     */
    public function isMaster(Request $request){
        $user = $request->userLogin;
        $master = CompanyMasterModel::leftJoin('company', 'company_master.company_id', '=', 'company.id')
            ->where('user_id', $user->id)
            ->whereNull('company.deleted_at')
            ->select('company_master.*', 'company.name as company_name','company.id as company_id')
            ->first();

        if($master){
            return json([
                'code' => 1,
                'data' =>  $master,
            ]);
        }

        return json([
            'code' => 0,
            'data' => [],
        ]);
    }

    /**
     * 获取公司员工列表（分页）
     * @param Request $request
     * @return \support\Response
     */
    public function memberList(Request $request){
        try {
            $user = $request->userLogin;
            
            // 验证用户权限
            $companyMaster = CompanyMasterModel::where('user_id', $user->id)->first();
            if (!$companyMaster) {
                throw new \Exception('您不是公司管理员');
            }

            $company = CompanyModel::where('id', $companyMaster->company_id)->first();
            if (!$company) {
                throw new \Exception('公司信息不存在');
            }

            // 获取分页参数
            $page = (int)$request->get('page', 1);
            $pageSize = (int)$request->get('page_size', 10);
            
            // 验证分页参数
            if ($page < 1) {
                throw new \Exception('页码参数错误');
            }
            
            // 限制每页最大数量
            if ($pageSize > 50) {
                $pageSize = 50;
            }

            // 查询公司所有员工
            $members = UserModel::where('company_id', $companyMaster->company_id)
                ->orderBy('created_at', 'desc')
                ->paginate($pageSize, ['*'], 'page', $page);

            // 处理员工数据，隐藏敏感信息
            $memberList = [];
            foreach ($members->items() as $member) {
                $memberList[] = [
                    'id' => $member->id,
                    'nickname' => $member->nickname,
                    'phone' => $member->safePhone(), // 使用脱敏的手机号
                    'headimg' => $member->headimg,
                ];
            }

            return json([
                'code' => 1,
                'msg' => '获取员工列表成功',
                'data' => [
                    'list' => $memberList,
                    'total' => $members->total(),
                    'current_page' => $members->currentPage(),
                    'per_page' => $members->perPage(),
                    'last_page' => $members->lastPage(),
                    'company' => [
                        'id' => $company->id,
                        'name' => $company->name,
                        'total_members' => UserModel::where('company_id', $companyMaster->company_id)->count()
                    ]
                ],
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null,
            ]);
        }
    }

    /**
     * 删除公司员工（将员工从公司中移除）
     * @param Request $request
     * @return \support\Response
     */
    public function removeMember(Request $request){
        try {
            $user = $request->userLogin;
            
            // 验证用户权限
            $companyMaster = CompanyMasterModel::where('user_id', $user->id)->first();
            if (!$companyMaster) {
                throw new \Exception('您不是公司管理员');
            }

            // 获取要删除的员工ID
            $input = $request->post('data');
            $userId = (int)$input['user_id'];
            if (!$userId) {
                throw new \Exception('员工ID不能为空');
            }

            // 查找要删除的员工
            $targetUser = UserModel::where('id', $userId)
                ->where('company_id', $companyMaster->company_id)
                ->first();
            
            if (!$targetUser) {
                throw new \Exception('员工不存在或不属于您的公司');
            }

            // 不能删除自己
            if ($targetUser->id === $user->id) {
                throw new \Exception('不能删除自己');
            }

            // 将员工的company_id重置为0，表示从公司中移除
            $targetUser->company_id = 0;
            $targetUser->save();

            return json([
                'code' => 1,
                'msg' => '员工已成功从公司中移除',
                'data' => null,
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null,
            ]);
        }
    }

    /**
     * 添加公司员工
     * @param Request $request
     * @return \support\Response
     */
    public function addMember(Request $request){
        try {
            $user = $request->userLogin;
            
            // 验证用户权限
            $companyMaster = CompanyMasterModel::where('user_id', $user->id)->first();
            if (!$companyMaster) {
                throw new \Exception('您不是公司管理员');
            }

            $company = CompanyModel::where('id', $companyMaster->company_id)->first();
            if (!$company) {
                throw new \Exception('公司信息不存在');
            }

            // 获取手机号参数
            $input = $request->post('data');
            $phone = trim($input['phone'] ?? '');
            
            if (empty($phone)) {
                throw new \Exception('手机号不能为空');
            }

            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
                throw new \Exception('手机号格式不正确');
            }

            // 查找用户
            $targetUser = UserModel::where('phone', $phone)->first();
            if (!$targetUser) {
                throw new \Exception('该手机号未注册会员');
            }

            // 检查用户是否已经是公司员工
            if ($targetUser->company_id == $companyMaster->company_id) {
                throw new \Exception('该用户已经是公司员工');
            }

            // 检查用户是否已经绑定其他公司
            if ($targetUser->company_id > 0) {
                throw new \Exception('该用户已绑定其他公司，无法添加');
            }

            // 将用户添加到公司
            $targetUser->company_id = $companyMaster->company_id;
            $targetUser->save();

            return json([
                'code' => 1,
                'msg' => '员工添加成功',
                'data' => [
                    'user' => [
                        'id' => $targetUser->id,
                        'nickname' => $targetUser->nickname,
                        'phone' => $targetUser->safePhone(),
                        'headimg' => $targetUser->headimg,
                    ]
                ],
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null,
            ]);
        }
    }

    public function getMyCompanyInfo(Request $request){
        $user = $request->userLogin;
        $companyMaster = CompanyMasterModel::where('user_id', $user->id)->first();
        if(!$companyMaster){
            return json([
                'code' => 0,
                'msg' => '您不是公司管理员',
                'data' => null,
            ]);
        }

        $company = CompanyModel::where('id', $companyMaster->company_id)->first();

        $cardTotal = CardModel::where('company_id', $companyMaster->company_id)->count();
        $company['card_total'] = $cardTotal;


        $companyKf = CompanyKfModel::where('company_ids', 'like', '%@'.$company->id.'@%')->first();
        if($companyKf){
            $company['kf_realname'] = $companyKf->realname;
            $company['kf_phone'] = $companyKf->phone;
        }else{
            $company['kf_realname'] = '';
            $company['kf_phone'] = '';
        }

        $company['person_total'] = UserModel::where('company_id', $company->id)->count();

        return json([
            'code' => 1,
            'msg' => '获取公司信息成功',
            'data' => $company,
        ]);
    }

    /**
     * 获取公司发布的所有卡片
     * @param Request $request
     * @return \support\Response
     */
    public function getCompanyCards(Request $request){
        try {
            $user = $request->userLogin;
            
            // 验证用户权限
            $companyMaster = CompanyMasterModel::where('user_id', '=',$user->id)->first();
            if (!$companyMaster) {
                throw new \Exception('您不是公司管理员');
            }

            $company = CompanyModel::find($companyMaster->company_id);
            if (!$company) {
                throw new \Exception('公司信息不存在');
            }

            // 获取分页参数
            $page = (int)$request->get('page', 1);
            $pageSize = (int)$request->get('page_size', 10);
            
            // 验证分页参数
            if ($page < 1) {
                throw new \Exception('页码参数错误');
            }
            
            // 限制每页最大数量
            if ($pageSize > 50) {
                $pageSize = 50;
            }

            // 查询公司发布的所有卡片
            $cards = CardModel::where('company_id', $companyMaster->company_id)
                ->where(function($query){
                    $query->whereNull('deleted_at')->orWhere('deleted_at', 0);
                })
                ->orderBy('created_at', 'desc')
                ->paginate($pageSize, ['*'], 'page', $page);

            // 处理卡片数据
            $cardList = [];
            foreach ($cards->items() as $card) {
                $item_total = CardItemModel::where('card_id', $card->id)->count();
                $used_total = CardItemModel::where('card_id', $card->id)->where('status', 1)->count();
                $cardList[] = [
                    'id' => $card->id,
                    'title' => $card->name,
                    'score' => $card->score,
                    'image' => $card->image,
                    'expired_days' => $card->expired_days,
                    'created_at' => date('Y-m-d H:i:s', $card->created_at),
                    'item_total' => $item_total,
                    'used_total' => $used_total,
                ];
            }

            return json([
                'code' => 1,
                'msg' => '获取公司卡片列表成功',
                'data' => [
                    'list' => $cardList,
                    'total' => $cards->total(),
                    'current_page' => $cards->currentPage(),
                    'per_page' => $cards->perPage(),
                    'last_page' => $cards->lastPage(),
                    'company' => [
                        'id' => $company->id,
                        'name' => $company->name,
                        'total_cards' => CardModel::where('company_id', $companyMaster->company_id)
                            ->whereNull('deleted_at')
                            ->count()
                    ]
                ],
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null,
            ]);
        }
    }

    /**
     * 获取卡片激活记录明细
     * @param Request $request
     * @return \support\Response
     */
    public function getCardUserList(Request $request){
        try {
            $user = $request->userLogin;
            
            // 验证用户权限
            $companyMaster = CompanyMasterModel::where('user_id', $user->id)->first();
            if (!$companyMaster) {
                throw new \Exception('您不是公司管理员');
            }

            // 获取卡片ID参数
            $cardId = $request->get('card_id');
            if (empty($cardId)) {
                throw new \Exception('卡片ID不能为空');
            }

            // 验证卡片是否存在且属于当前公司
            $card = CardModel::where('id', $cardId)
                ->where('company_id', $companyMaster->company_id)
                ->first();
            if (!$card) {
                throw new \Exception('卡片不存在或不属于您的公司');
            }

            // 获取分页参数
            $page = (int)$request->get('page', 1);
            $pageSize = (int)$request->get('page_size', 10);
            
            // 验证分页参数
            if ($page < 1) {
                throw new \Exception('页码参数错误');
            }
            
            // 限制每页最大数量
            if ($pageSize > 50) {
                $pageSize = 50;
            }

            // 获取搜索参数
            $searchPhone = $request->get('search_phone', '');

            // 构建查询
            $query = CardUserModel::where('card_id', $cardId);
            
            // 如果提供了手机号搜索参数，添加搜索条件
            if (!empty($searchPhone)) {
                $query->where('phone', 'like', '%'.$searchPhone.'%');
            }
            
            // 查询卡片激活记录
            $cardUsers = $query->orderBy('created_at', 'desc')
                ->paginate($pageSize, ['*'], 'page', $page);
            
            // 处理激活记录数据
            $data = [];
            foreach ($cardUsers->items() as $item) {
                $user = UserModel::find($item->user_id);
                if ($user) {
                    $data[] = [
                        'id' => $item->id,
                        'score' => $item->score,
                        'use_score' => $item->use_score,
                        'activated_at' => date('Y-m-d H:i:s', $item->created_at), // 激活时间
                        'user' => [
                            'id' => $user->id,
                            'nickname' => $user->nickname,
                            'phone' => $user->safePhone() // 激活手机号
                        ]
                    ];
                }
            }

            return json([
                'code' => 1,
                'msg' => '获取卡片激活记录成功',
                'data' => [
                    'list' => $data,
                    'total' => $cardUsers->total(),
                    'current_page' => $cardUsers->currentPage(),
                    'per_page' => $cardUsers->perPage(),
                    'last_page' => $cardUsers->lastPage(),
                    'card' => [
                        'id' => $card->id,
                        'name' => $card->name,
                        'score' => $card->score
                    ]
                ],
            ]);
            
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => null,
            ]);
        }
    }
}
